# crawler/mock_crawler.py

import time
import random
from typing import List, Dict, Any, Callable
from data.data_store import DataStore


def start_mock_crawling(
    platform: str,
    ctype: str,
    params: Dict[str, Any],
    data_store: DataStore,
    update_callback: Callable,
    status_callback: Callable[[str, str], None],
    finish_callback: Callable
):
    """
    模拟爬虫：生成假商品数据，并逐步插入到 DataStore 中
    """
    keywords = params.get("keywords", ["默认关键词"])
    min_sales = params.get("min_sales")
    max_sales = params.get("max_sales")
    min_price = params.get("min_price")
    max_price = params.get("max_price")
    exclude_brands = params.get("exclude_brands", set())
    enable_dedup = params.get("enable_dedup", False)

    # 模拟品牌库（用于排除）
    all_brands = ["苹果", "华为", "小米", "OPPO", "vivo", "三星", "荣耀", "一加", "realme", "魅族"]
    titles = [
        f"{brand} 新款智能手机 {kw}" for brand in all_brands for kw in keywords[:2]
    ] or [f"{platform}{ctype}商品示例"]

    collected_links = set()  # 用于去重
    total_items = random.randint(8, 15)  # 模拟采集 8~15 条数据

    status_callback(f"模拟采集 {platform} - {ctype}，共约 {total_items} 条...", "blue")

    for i in range(total_items):
        if not keywords:
            title = f"无关键词商品 {i+1}"
        else:
            title = random.choice(titles)

        brand = title.split(" ")[0] if title.split(" ") else "未知品牌"
        if brand in exclude_brands:
            continue  # 跳过排除品牌

        price = round(random.uniform(99.9, 5999.9), 2)
        if min_price is not None and price < min_price:
            continue
        if max_price is not None and price > max_price:
            continue

        sales = random.randint(10, 10000)
        if min_sales is not None and sales < min_sales:
            continue
        if max_sales is not None and sales > max_sales:
            continue

        link = f"https://mock.{platform.lower()}.com/item/{random.randint(100000, 999999)}"
        if enable_dedup and link in collected_links:
            continue
        collected_links.add(link)

        item = {
            "shop": f"{brand}官方旗舰店",
            "title": title,
            "link": link,
            "price": f"¥{price}",
            "rating": f"{round(random.uniform(4.5, 5.0), 1)}分",
            "keyword": random.choice(keywords) if keywords else "",
            "category": random.choice(params.get("selected_categories") or ["未分类"]),
            "sales": str(sales)
        }

        data_store.add_item(platform, ctype, item)

        # 模拟网络延迟
        time.sleep(0.3)

        # 更新 UI（通过回调）
        status_callback(f"已采集 {i+1}/{total_items} 条...", "orange")
        update_callback(delay=10, func=None)  # 刷新表格

    finish_callback()